﻿using Exiled.API.Features;
using MEC;
using RgCore.Database;
using RgCore.Modules;
using RgCore.PlayerHud;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace RollingBroadcasts
{
    public class Config : IConfig
    {
        [Description("冷却时间")]
        public int Time { get; set; } = 360;
        [Description("表名")]
        public string TableName { get; set; } = "cdcp_broadcasts";
    }
    public class RBPlugin : RgPlugin
    {
        public override string Name => "公告轮换插件";
        public override string Id => "rolling_broadcasts";

        public override object Config { get; set; } = new Config();
        public string[] Broadcasts { get; set; } = null;
        public CoroutineHandle Coroutine { get; set; }
        private int Index = 0;
        private int Updates = 0;
        public override void OnDisabled()
        {
            base.OnDisabled();
            Timing.KillCoroutines(Coroutine);
        }
        public async Task GetBroadcasts()
        {
            QueryCommandRequest cmd = new QueryCommandRequest(((Config)Config).TableName, null, false, "content");
            var result = await cmd.GetResponseResult();
            Broadcasts = result.Select(x => x["content"] as string).ToArray();
        }
        public override async void OnEnabled()
        {
            base.OnEnabled();
            await GetBroadcasts();
            if (Broadcasts.Length > 0)
            {
                Coroutine = Timing.RunCoroutine(Update(((Config)Config).Time));
            }
        }
        private IEnumerator<float> Update(int sec)
        {
            while (true)
            {
                if (!Broadcasts.TryGet(Index, out string text))
                {
                    Index = 0;
                    Updates++;
                    if (Updates == 3)
                    {
                        _ = GetBroadcasts();
                        Updates = 0;
                    }
                }
                else
                {
                    Index++;
                }
                HudHandler.SendRawMsg("rolling_broadcasts", new string[]
                {
                    "<color=yellow>| <color=#FF5555>定时公告</color> |</color>",
                    text
                }, 8, ScreenLocation.Top, false, Player.List.ToArray());
                yield return Timing.WaitForSeconds(sec);
            }
        }
    }
}
